package com.example.exception;

import com.example.common.ApiRestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * 全局拦截异常,处理统一异常的Handler
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理系统异常
     *
     * @param
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleException(Exception e) {
        log.error("Default Exception", e);
        return ApiRestResponse.error(ImoocMallExceptionEnum.SYSTEM_ERROR);
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ImoocMallException.class)
    @ResponseBody
    public Object handleImoocMallException(ImoocMallException e) {
        log.error("ImoocMallException", e);
        return ApiRestResponse.error(e.getCode(), e.getMessage());
    }
//    @valid的异常处理
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public ApiRestResponse handMethodArgumentNotValidException(MethodArgumentNotValidException e){
    log.error("MethodArgumentNotValidException", e);
    return handleBindingResult(e.getBindingResult());
}
    private ApiRestResponse handleBindingResult(BindingResult result){
        List<String> list=new ArrayList<>();
        if(result.hasErrors()){
            List<ObjectError> allErrors = result.getAllErrors();
            for(ObjectError objectError : allErrors){
                String messge = objectError.getDefaultMessage();
                list.add(messge);
            }
        }
        if(list.size()==0){
            return ApiRestResponse.error(ImoocMallExceptionEnum.REQUEST_ERROR);
        }
        return ApiRestResponse.error(ImoocMallExceptionEnum.REQUEST_ERROR.getCode(),list.toString());
    }
}
